<?php

//header('Content-type: text/html; charset=utf-8');
//  CardKey    query for stars
//  CardKey+StarName  add star and do query
//  StarKey  delete star

include "../../dbaccess.php";
$connector = mysql_pconnect($dbserver, $dbuser, $dbpassword) or die(mysql_error($connector));
unset ($dbuser, $dbpassword, $dbserver);

mysql_select_db('gasilvis_EggenCards2') or die(mysql_error());

$Note= ""; // use to msg special results; 

// Delete request?
if (isset($_GET['StarKey'])) { 
   $i= trim($_GET['StarKey']);
   $q= "DELETE FROM Star WHERE StarKey=".$i;
   $dataReturned = mysql_query($q) or die(mysql_error());
   file_put_contents("transaction.log", $q."\n", FILE_APPEND | LOCK_EX);
   // return;  fall through
}

if (isset($_GET['CardKey'])) {
   $ck= trim($_GET['CardKey']);
   if (isset($_GET['StarName'])) {
      //$sn= urldecode(trim($_GET['StarName']));
      $sn= trim($_GET['StarName']);
      $UserID= trim($_GET['UserID']);
      // validate star name
      $val= false;
      $xml= simplexml_load_file("http://vizier.cfa.harvard.edu/viz-bin/nph-sesame/-oxI/~S?".urlencode($sn));
 //file_put_contents("transaction.log", $sn."\n", FILE_APPEND | LOCK_EX);
      if($xml->Target->Resolver) { 
         foreach ($xml->Target->Resolver->children() as $child) {
            if( $child->getName() === 'alias') {
 //file_put_contents("transaction.log", $child."\n", FILE_APPEND | LOCK_EX);
               //$i= str_replace(' ','',$child); // no blanks
               if(0== strcasecmp($sn, $child)) {
                  $val= true;
                  break;
               }
            }   
         }   
      }
      if($val) {
         // add the star
         $q= "INSERT INTO Star (StarName, CardKey, UserID) VALUES (\"".$sn."\", ".$ck.", ".$UserID.")";
         $dataReturned = mysql_query($q) or die(mysql_error());
         file_put_contents("transaction.log", $q."\n", FILE_APPEND | LOCK_EX);
         //return;  fall through
      } else {
         $Note= "Star reference not in proper form; try again.";
      }   
   }   
   // else its a query
   $q= "SELECT * FROM Star";
   $where= $and= false;

   $q= $q.($where?"":" WHERE").($and?" AND":"")." CardKey=".$ck;
   $where= $and= true;
   
   $q= $q." ORDER BY StarKey LIMIT 3000";

   $callback = trim($_GET['callback']);

   $dataReturned = mysql_query($q) or die(mysql_error());

   echo $callback;
   echo '([';
   echo "{\"Note\":\"".urlencode($Note)."\"},";
   $f= false;
   while($row = mysql_fetch_array($dataReturned)){
      if($f) echo ',';  $f= true;
      echo '{';
      $i= $row['StarName'];   echo "\"StarName\":\"".urlencode($i)."\",";
      $i= $row['CardKey'];    echo "\"CardKey\":$i,";
      $i= $row['StarKey'];    echo "\"StarKey\":$i";
      echo '}';
   }

   echo '])';
}

?>